<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;
use app\common\model\RechargeWithdrawal;
use app\common\model\Strategy;
use think\db\Query;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{

    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }

        //待处理入金申请
        $rechargeNum = RechargeWithdrawal::where(['status'=>1,'type'=>1])->count();
        $rechargeList = RechargeWithdrawal::where('1=1')
            ->where(['status'=>1,'type'=>1])
            ->order('id desc')
            ->group('user_id')
            ->limit(5)
            ->select();
        $rechargeStr = $this->userStr(User::whereIn('id',$rechargeList->column('user_id'))->select());
        //待处理提现申请
        $withdrawalNum = RechargeWithdrawal::where(['status'=>1,'type'=>2])->count();
        $withdrawalList = RechargeWithdrawal::where('1=1')
            ->where(['status'=>1,'type'=>2])
            ->order('id desc')
            ->group('user_id')
            ->limit(5)
            ->select();
        $withdrawalStr = $this->userStr(User::whereIn('id',$withdrawalList->column('user_id'))->select());
        //亏损预警
        $strategyNum = Strategy::where('income_ratio','<=','-0.7')->count();
        $strategyList = Strategy::where('income_ratio','<=','-0.7')
            ->where(['status'=>1])
            ->group('user_id')
            ->limit('5')
            ->select();
        $strategyStr = $this->userStr(User::whereIn('id',$strategyList->column('user_id'))->select());
        //待优化服务统计
        $optimizeNum = User::where(function (Query $query){
            $query->whereNull('real_name')
                ->whereOr('bank_num is null')
                ->whereOr('pay_pwd is null')
                ->whereOr('money','0');
        })->where('jointime','<',time() - 3 * 3600 * 24)->count();
        $optimizeList = User::where(function (Query $query){
            $query->whereNull('real_name')
                ->whereOr('bank_num is null')
                ->whereOr('pay_pwd is null')
                ->whereOr('money','0');
        })->where('jointime','<',time() - 3 * 3600 * 24)->limit(5)->select();
        $optimizeStr = $this->userStr($optimizeList);


        $this->view->assign([
            //总会员数
            'totaluser'         => User::count(),
            //累积入金金额
            'allRechargeMoney'         => $this->format_number(RechargeWithdrawal::where(['status'=>2,'type'=>1])->sum('money')),
            //累积提现金额
            'allWithdrawalMoney'         =>  $this->format_number(RechargeWithdrawal::where(['status'=>2,'type'=>2])->sum('money')),
            //现有入金金额
            'userAllMoney'=>$this->format_number(User::sum('money')),

            //待处理入金申请
            'rechargeNum'=>$rechargeNum,
            'rechargeStr'=>$rechargeStr,
            //待处理提现申请
            'withdrawalNum'=>$withdrawalNum,
            'withdrawalStr'=>$withdrawalStr,
            //亏损预警
            'strategyNum'=>$strategyNum,
            'strategyStr'=>$strategyStr,
            //待优化服务统计
            'optimizeNum'=>$optimizeNum,
            'optimizeStr'=>$optimizeStr,


            'todayusersignup'   => User::whereTime('jointime', 'today')->count(),
            'todayuserlogin'    => User::whereTime('logintime', 'today')->count(),
            'sevendau'          => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau'         => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu'          => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu'          => User::whereTime('jointime', '-7 days')->count(),

        ]);

        //每日入金图表
        $dayRecharge = RechargeWithdrawal::where(['status'=>2,'type'=>1])
            ->field('FROM_UNIXTIME(status_time,"%Y-%m-%d") as date,sum(money) as sum_money')
            ->select()->column('sum_money','date');

        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $data = array_fill_keys($column, 0);
        foreach ( $dayRecharge as $key=>$value ){
            $data[$key] = $value;
        }

        $this->assignconfig('column', array_keys($data));
        $this->assignconfig('userdata', array_values($data));

        return $this->view->fetch();
    }


    protected function userStr($userList){
        $rechargeStr = '';
        foreach ( $userList as $userInfo ){
            $rechargeStr .= ($userInfo->real_name ?? '未实名');
            $rechargeStr .= ',';
        }
        $rechargeStr = substr($rechargeStr,0,-1);
        return (string)$rechargeStr;
    }

    //格式化数字
    protected function format_number($num)
    {
        if(is_numeric($num)){
            if(floor($num) >= 10000){
                if(strpos($num,'.')){
                    $arr = explode('.',$num);
                    $formatted_num = number_format($arr[0]);
                    if(isset($arr[1]) && !empty($arr[1])){
                        return $formatted_num .'.'. $arr[1];
                    }
                }
                return number_format($num);
            }
            return $num;
        }
    }
}
